import React, { useEffect, useState, useRef, useMemo, forwardRef } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { message } from 'antd';
import { uploadImage } from '../../api/UploadApi';
import './NewsEditor.scss';

interface NewsEditorProps {
  content?: string;
  getContent: (htmlContent: string) => void;
}

// 编辑器实例类型
interface QuillEditor {
  insertEmbed: (index: number, type: string, url: string) => void;
  getSelection: (focus: boolean) => { index: number; length: number };
  setSelection: (index: number, length: number) => void;
}

// 自定义 ReactQuill 类型，包含 getEditor 方法
interface CustomReactQuill extends React.Component {
  getEditor: () => QuillEditor;
}

// 创建一个转发引用的 ReactQuill 组件
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const QuillWrapper = forwardRef<CustomReactQuill, any>((props, ref) => (
  <ReactQuill ref={ref} {...props} />
));

const NewsEditor: React.FC<NewsEditorProps> = ({ content, getContent }) => {
  const [editorContent, setEditorContent] = useState<string>(content || '');
  const quillRef = useRef<CustomReactQuill>(null);
  
  useEffect(() => {
    if (content) {
      setEditorContent(content);
    }
  }, [content]);

  // 图片处理函数
  const imageHandler = () => {
    // 创建文件选择器
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.click();
    
    // 监听文件选择
    input.onchange = async () => {
      if (input.files && input.files.length > 0) {
        const file = input.files[0];
        
        // 检查文件大小 (5MB限制)
        if (file.size > 5 * 1024 * 1024) {
          message.error('图片大小不能超过5MB');
          return;
        }
        
        // 创建FormData
        const formData = new FormData();
        formData.append('file', file);
        
        try {
          // 显示上传中提示
          message.loading('图片上传中...', 0);
          
          // 获取编辑器实例，确保能够插入图片
          const editor = quillRef.current?.getEditor();
          if (!editor) {
            message.error('编辑器实例未找到');
            return;
          }
          
          // 获取当前光标位置
          const range = editor.getSelection(true);
          
          // 使用 uploadImage API 上传图片
          const result = await uploadImage(file);
          const imageUrl = result.url;
          
          // 在光标位置插入图片
          editor.insertEmbed(range.index, 'image', imageUrl);
          
          // 移动光标到图片后
          editor.setSelection(range.index + 1, 0);
          
          // 关闭上传提示
          message.destroy();
          message.success('图片上传成功');
        } catch (error) {
          console.error('图片上传失败:', error);
          message.destroy();
          message.error('图片上传失败');
        }
      }
    };
  };

  const handleChange = (value: string) => {
    setEditorContent(value);
    getContent(value);
  };

  // 自定义工具栏选项和回调
  const modules = useMemo(() => ({
    toolbar: {
      container: [
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'align': [] }],
        ['link', 'image'],
        ['clean']
      ],
      handlers: {
        image: imageHandler
      }
    },
  }), []);

  const formats = [
    'header',
    'bold', 'italic', 'underline', 'strike',
    'list', 'bullet',
    'color', 'background',
    'align',
    'link', 'image'
  ];

  return (
    <div className="news-editor">
      <QuillWrapper
        ref={quillRef}
        theme="snow"
        value={editorContent}
        onChange={handleChange}
        modules={modules}
        formats={formats}
        placeholder="请输入内容..."
      />
      <div className="news-editor-tips">
        支持直接粘贴图片或使用工具栏上传图片
      </div>
    </div>
  );
};

export default NewsEditor; 